Ext.ns('journal.home');

// {{{
journal.home.EntryExplorerPanel = Ext.extend(Ext.tree.TreePanel, (function() {

    //var logger = journal.LoggerFactory.getLogger("journal.EntryExplorerPanel");

    /** Counter to number of branches opened */
    var initialLoadCount = 0;

    /**
     * @param node
     * @param xy - location where to pop the context menu.
     * @param node
     */
    var showContextMenu = function(node, treeContextMenu, xy, scope) {
        node.select();
        var isRoot = node.text == 'Root';
        Ext.getCmp('mnuAddItem').setVisible(!isRoot && !node.isLeaf());
        Ext.getCmp('mnuEditItem').setVisible(node.isLeaf());
        Ext.getCmp('mnuDelete').setVisible(!isRoot && !node.hasChildNodes());
        Ext.getCmp('mnuAddFolder').setVisible(!node.isLeaf());
        Ext.getCmp('mnuProperties').setVisible(!isRoot);
        if (xy.length != null) {
            treeContextMenu.showAt(xy);
        } else {
            treeContextMenu.show(xy);
        }
    };

    var editNodeHandler = function() {
        var selectedNode = Ext.getCmp(journal.Constant.Id.ENTRY_TREE).getSelectionModel().getSelectedNode();
        journal.home.MainHandler.addRecentFileItem(selectedNode);
        journal.home.Main.editorPanel.newTabHandler(selectedNode);
    };

    /**
     * Will display the properties dialog for a branch or node.
     */
    var propertiesHandler = function() {
        var selectedNode = Ext.getCmp(journal.Constant.Id.ENTRY_TREE).getSelectionModel().getSelectedNode();
        var win = new journal.home.NodePropertyDialog({
            node : selectedNode
        });
        win.on('render', function(w) {
            w.width = 400;
        });
        win.show();
    };

    return {
        // configurables
        // anything what is here can be configured from outside

        // {{{
        /**
         * Will reload the tree.
         */
        reloadTreeHandler : function(tree) {
            journal.home.Main.explorerPanel.codeExplorer.getTopToolbar().get(1).setValue('');
            journal.home.EntryExplorerPanel.filter.clear();
            journal.home.EntryExplorerPanel.filter.filtered = {};
            tree.getRootNode().reload();
            journal.StateService.restoreFlag = true;
            journal.StateService.restore(journal.StateService.ST_TREE, function(arg) {
                journal.home.Main.explorerPanel.codeExplorer.expandPath(arg);
            }.createDelegate(this));
            journal.StateService.restoreFlag = false;
        },

        nodesInRecent : [],
        initComponent : function() {

            var treeContextMenu = new Ext.menu.Menu({
                items : [
                        {
                            id : 'mnuAddFolder',
                            text : 'Add Branch',
                            iconCls : 'icon-addFolder',
                            handler : function(menuItem, event) {
                                var targetNode = Ext.getCmp(journal.Constant.Id.ENTRY_TREE).getSelectionModel()
                                        .getSelectedNode();
                                journal.home.EntryExplorerHandler.addFolderHandler(targetNode);
                            }
                        },
                        {
                            id : 'mnuAddItem',
                            text : 'Add Item',
                            iconCls : 'icon-addItem',
                            handler : function() {
                                this.callbackNewItemTab();
                            }.createDelegate(this)
                        },
                        {
                            id : 'mnuEditItem',
                            text : 'Edit',
                            iconCls : 'icon-editItem',
                            handler : function() {
                                editNodeHandler();
                            }
                        },
                        {
                            id : 'mnuDelete',
                            text : 'Delete',
                            iconCls : 'icon-removeItem',
                            handler : function() {
                                var selectedNode = Ext.getCmp(journal.Constant.Id.ENTRY_TREE).getSelectionModel()
                                        .getSelectedNode();
                                journal.home.EntryExplorerHandler.deleteNodeHandler(selectedNode);
                            }
                        }, {
                            id : 'mnuProperties',
                            text : 'Properties',
                            iconCls : 'icon-properties',
                            handler : function() {
                                propertiesHandler();
                            }
                        } ]
            });

            journal.home.EntryExplorerPanel.filter = new journal.ui.TreeFilter(this);

            var treeLoader = new Ext.tree.TreeLoader({
                dataUrl : 'home?action=getChildren',
                listeners : {
                    beforeload : function(treeLoader, node) {
                        this.baseParams.parentId = node.id;
                    },
                    load : function(tree, expandedNode, resp) {
                        if (expandedNode.text != 'Root') {
                            initialLoadCount++;
                            /**
                             * Load only after all expanded tree branches has been expanded.
                             */
                            if (initialLoadCount == journal.StateService.getCount(journal.StateService.ST_TREE)) {
                                initialLoadCount += 666;
                                journal.StateService.restoreFlag = true;

                                var tabOrder = ',';
                                journal.StateService.restore(journal.StateService.ST_TAB, function(path) {
                                    tabOrder += path + ',';
                                });

                                var comesBefore = function(a, b) {
                                    var posA = tabOrder.indexOf(a);
                                    var posB = tabOrder.indexOf(b);
                                    return posA < posB;
                                };

                                var stack = new Array();
                                journal.StateService.restore(journal.StateService.ST_TABORDER, function(path) {
                                    //var id = path.substring(path.lastIndexOf('/') - 1);
                                    this.expandPath(path, 'id', function(a, targetNode) {
                                        var pos = 0;
                                        for (pos = 0; pos < stack.length; pos++) {
                                            if (comesBefore(path, stack[pos])) {
                                                break;
                                            }
                                        }

                                        this.ownerCt.ownerCt.get(journal.Constant.Id.EDITORPANEL).newTabHandler(
                                                targetNode, pos);
                                    }.createDelegate(this));
                                    stack.push(path);
                                }.createDelegate(this));
                                journal.StateService.restoreFlag = false;
                            }
                        }
                    }.createDelegate(this),
                    loadexception : function() {
                    }
                }
            });

            var rootNode = new Ext.tree.AsyncTreeNode({
                id : 'b-1',
                text : 'Root',
                expanded : true,
                editable : false,
                expandable : true
            });

            // hard coded config - cannot be changed from outside
            var config = {
                title : 'Entry Explorer',
                loader : treeLoader,
                root : rootNode,
                rootVisible : false,
                autoScroll : true,
                closable : false,
                enableKeyEvents : true,
                enableDD : true,
                tbar : {
                    id : 'entryExplorerToolbar',
                    xtype : 'journal.home.EntryExplorerToolbar'
                }

            };

            this.on('contextmenu', function(node) {
                showContextMenu(node, treeContextMenu, node.ui.getAnchor(), this);
            }.createDelegate(this));

            this.on('containercontextmenu', function(tree, event, c) {
                showContextMenu(this.root, treeContextMenu, event.xy, this);
            }.createDelegate(this));

            /**
             * Need to reset the 4 states on success/fail of move.
             */
            this.on('beforemovenode', function(tree, node, oldParent, newParent, index) {
                return journal.home.EntryExplorerHandler.beforeMoveNodeHandler(this, {
                    'tree' : tree,
                    'node' : node,
                    'oldParent' : oldParent,
                    'newParent' : newParent,
                    'index' : index
                });
            }.createDelegate(this));

            this.on('nodedragover', function(obj) {
                obj.cancel = obj.dropNode.isLeaf() && obj.target.text == 'Root';
            });

            this.treeSorter = new Ext.tree.TreeSorter(this, {
                folderSort : true,
                dir : "asc"
            });

            this.on('click', function() {
                journal.StateService.restoreFlag = false;
            });

            this.on('afterrender', function(c) {
                this.treeEditor = new Ext.tree.TreeEditor(this);
                this.dragZone.lock();
            }.createDelegate(this));

            this.on('render', function(treePanel) {
                Ext.EventManager.on(treePanel.el.dom, 'keypress',
                        function(e) {
                            var selectedNode = Ext.getCmp(journal.Constant.Id.ENTRY_TREE).getSelectionModel()
                                    .getSelectedNode();
                            if (e.DELETE == e.getKey()) {
                                if (selectedNode.id != 'b-1' && !selectedNode.hasChildNodes()) {
                                    journal.home.EntryExplorerHandler.deleteNodeHandler(selectedNode);
                                }
                            } else if (e.F2 == e.getKey()) {
                                var tree = Ext.getCmp(journal.Constant.Id.ENTRY_TREE);
                                var editor = tree.treeEditor;
                                editor.startEdit(selectedNode.ui.getTextEl());
                            } else if (e.ENTER == e.getKey()) {
                                if (selectedNode.isLeaf()) {
                                    journal.home.MainHandler.addRecentFileItem(selectedNode);
                                    journal.home.Main.editorPanel.newTabHandler(selectedNode);
                                } else {
                                    selectedNode.expand();
                                }
                                e.stopEvent();
                            }
                        }.createDelegate(this));

                this.getTopToolbar().get('tbbRefreshTree').on('click', function(b) {
                    if (journal.home.Main.editorPanel.items.length > 0) {
                        Ext.Msg.show({
                            title : 'Confirm Refresh',
                            msg : 'Refreshing will close all open tabs, proceed?',
                            buttons : Ext.Msg.OKCANCEL,
                            fn : function(btn) {
                                if (btn == 'ok') {
                                    while (journal.home.Main.editorPanel.items.length > 0) {
                                        var actTab = journal.home.Main.editorPanel.activeTab;
                                        actTab.fireEvent('close', actTab);
                                    }
                                    this.reloadTreeHandler(this);
                                }
                            }.createDelegate(this),
                            icon : Ext.MessageBox.QUESTION
                        });
                    } else {
                        this.reloadTreeHandler(this);
                    }
                }.createDelegate(this));
            }.createDelegate(this));

            //            this.on('resize', function(comp, adjWidth, adjHeight, rawWidth, rawHeight) {
            //                var minWidth = 230;
            //                if (rawWidth < minWidth) {
            //                    comp.setWidth(minWidth);
            //                }
            //            });

            var selModel = this.getSelectionModel();
            selModel.on('selectionchange',
                    function(selModel, node) {
                        if (!journal.StateService.restoreFlag && node != null) {
                            Ext.getCmp(journal.home.EntryExplorerToolbar.ButtonId.CollapseAll).setDisabled(
                                    !node.hasChildNodes() || !node.isExpanded());
                            Ext.getCmp(journal.home.EntryExplorerToolbar.ButtonId.ExpandAll).setDisabled(
                                    !node.hasChildNodes());
                        }

                    });

            // apply config
            Ext.apply(this, Ext.apply(this.initialConfig, config));

            // call parent
            journal.home.EntryExplorerPanel.superclass.initComponent.apply(this, arguments);

        } // e/o function initComponent

    // }}}
    };
})()); // e/o extend

// register xtype
Ext.reg('journal.home.EntryExplorerPanel', journal.home.EntryExplorerPanel);
// }}}
